﻿using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;


namespace GKScoreQueryHelper
{
    public static class Utils
    {
      
        /// <summary>
        /// 把用逗号分隔的一组字符串中每个都用单引号包围。
        /// 如：张三,李四,王五 修改为 '张三','李四','王五'
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string QuoteString(string s)
        {
            return string.Format("'{0}'", s.Replace(",", "','"));
        }


        /// <summary>
        /// 返回当前主机的IP地址
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetIPAddress()
        {
            string ip = "";
            try
            {
                //WebClient MyWebClient = new WebClient();
                //MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据

                HttpClient client = new HttpClient();
                string pageHtml=await client.GetStringAsync("http://www.net.cn/static/customercare/yourip.asp");


                //Byte[] pageData = MyWebClient.DownloadData("http://www.net.cn/static/customercare/yourip.asp"); //从指定网站下载数据

                //string pageHtml = Encoding.Default.GetString(pageData);  //如果获取网站页面采用的是GB2312，则使用这句

                //string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8，则使用这句

                //string[] str = HtmlHelper.GetElementsByTagName(pageHtml, "h2");

                string regp = "<h2>(.*)</h2>";
                Regex reg = new Regex(@regp, RegexOptions.IgnoreCase);
                if (reg.IsMatch(pageHtml))
                {
                    Match match = reg.Match(pageHtml);
                    ip = match.Groups[1].Value;
                }
                //string[] str1 = str[0].Replace("<h2>", "").Split(',');

                //ip = str1[0];
            }
            catch (WebException webEx)
            {
                webEx.Message.ToString();
            }
            return ip;
        }


        /// <summary>
        /// 从html中通过正则找到ip信息(只支持ipv4地址)
        /// </summary>
        /// <param name="pageHtml"></param>
        /// <returns></returns>
        public static bool Authorized(String url)
        {

            TimeSpan timeOut = TimeSpan.FromSeconds(10);
            string pageHtml = string.Empty;

            using HttpClient MyWebClient = new HttpClient();
            MyWebClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
            //Task<string> task = MyWebClient.GetStringAsync(url);
            //if (task.Wait(timeOut))
            //{
            //    pageHtml = task.Result;
            //    string reg = @"\bauthorized\b:([true|false]+)";
            //    Match m = Regex.Match(pageHtml, reg);
            //    bool authorized = bool.Parse(m.Groups[1].Captures[0].Value);
            //    return authorized;
            //}
            //else
            //{
            //    return false;
            //}



            Task<string> task = MyWebClient.GetStringAsync(url);

            try
            {
                if (task.Wait(timeOut))
                {
                    pageHtml = task.Result;
                    string reg = @"\bauthorized\b:([true|false]+)";
                    Match m = Regex.Match(pageHtml, reg);
                    bool authorized = bool.Parse(m.Groups[1].Captures[0].Value);
                    return authorized;
                }
                else
                {

                    return false;
                }

            }
            catch (System.AggregateException)
            {
                return false;
            }



            //验证ipv4地址
            //using (var timeoutCancellationTokenSource = new CancellationTokenSource())
            //{
            //    Task<string> task = new Task<string>(async () => {
            //        using(HttpClient httpClient = new HttpClient())
            //        {
            //            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");



            //            pageHtml = await httpClient.GetStringAsync(url).Wait(timeoutLong);

            //        }





            //        return url;
            //    },timeoutCancellationTokenSource.Token);
            //    if ( task.Wait(timeoutLong, timeoutCancellationTokenSource.Token))
            //    {

            //        using (HttpClient httpClient = new HttpClient())
            //        {
            //            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");



            //            //pageHtml = await httpClient.GetStringAsync(url);


            //        }




            //        string reg = @"\bauthorized\b:([true|false]+)";

            //        Match m = Regex.Match(pageHtml, reg);
            //        bool authorized = bool.Parse(m.Groups[1].Captures[0].Value);
            //        return authorized;
            //    }
            //    else
            //    {
            //        timeoutCancellationTokenSource.Cancel();
            //        return false;
            //    }
            //}
        }


        public static Dictionary<string, int> GetFields(string fileName)
        {
            Dictionary<string, int> dic = [];
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                var wb = WorkbookFactory.Create(fs);
                var sh = wb.GetSheetAt(0);
                var row = sh.GetRow(0);
                for (int i = 0; i < row.PhysicalNumberOfCells; i++)
                {
                    var cell = row.GetCell(i);
                    dic.Add(cell.StringCellValue, i);
                }
                wb.Close();
                fs.Close();
            }
            return dic;
        }

        public static Dictionary<string,int> GetFieldsNames(this ISheet sh)
        {
            Dictionary<string, int> dic = [];
            var row = sh.GetRow(0);
            for (int i = 0; i < row.PhysicalNumberOfCells; i++)
            {
                var cell = row.GetCell(i);
                dic.Add(cell.StringCellValue, i);
            }
            return dic;
        }



        public static string? ValideFields(string fields, Dictionary<string, int> dic)
        {
            string deletionFields = string.Empty;
            string[] fs = fields.Split(',');
            foreach (var f in fs)
            {
                if (!dic.ContainsKey(f))
                {
                    deletionFields = f;
                    break;

                }
            }
            return deletionFields;
        }
    }
}
